package es.udc.fic.hamNeggs.web;

import org.apache.log4j.Logger;

import es.udc.fic.hamNeggs.dao.InputUser;
import es.udc.fic.hamNeggs.manager.ProjectManager;
import es.udc.fic.hamNeggs.manager.UserManager;
import es.udc.fic.hamNeggs.manager.WorksManager;
import es.udc.fic.hamNeggs.pojo.User;
import es.udc.fic.hamNeggs.pojo.Works;
import es.udc.fic.hamNeggs.pojo.Works.Rol;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;

/**
 * Servlet implementation class WorkDetails
 */
public class WorkDetails extends HttpServlet {
    private static final long   serialVersionUID = 1L;
    private final static Logger LOG              = Logger.getLogger(WorkDetails.class.getName());

    /**
     * @see HttpServlet#HttpServlet()
     */
    public WorkDetails() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        final HttpSession session = request.getSession(true);

        final Long myProject = (Long) session.getAttribute("project");
        final UserManager usrmng = new UserManager();
        final ArrayList<InputUser> allUsers = new ArrayList<InputUser>();
        for (final User w : usrmng.getUserList()) {
            final InputUser user = new InputUser();
            user.setUser(w);
            allUsers.add(user);
        }

        request.setAttribute("allUsers", allUsers);

        if ((request.getParameter("id") != null && request.getParameter("id") != "") || (request.getAttribute("usrid") != null && request.getAttribute("usrid").toString() != "")) {
            final WorksManager wrkmng = new WorksManager();
            if (request.getParameter("id") != null)
                request.setAttribute("usrid", request.getParameter("id"));
            final Works w = wrkmng.getWorks(new Long(request.getAttribute("usrid").toString()), myProject);
            if (w != null)
                request.setAttribute("usrrol", w.getRol().getString());
            wrkmng.close();
        }

        usrmng.close();
        request.getRequestDispatcher("/works_detail.jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        final HttpSession session = request.getSession(true);

        final Long myProject = (Long) session.getAttribute("project");

        final WorksManager wrkmng = new WorksManager();
        final ProjectManager prjmng = new ProjectManager();
        final UserManager usrmng = new UserManager();

        Works wrk = wrkmng.getWorks(new Long(request.getParameter("user")), myProject);

        try {
            switch (request.getParameter("action")) {
                case "Add":
                    if (wrk == null) {
                        wrk = new Works();
                        wrk.setUser(usrmng.getUser(new Long(request.getParameter("user"))));
                        wrk.setDateStart(new Date(Calendar.getInstance().getTimeInMillis()));
                        wrk.setProject(prjmng.getProject(new Long(myProject)));
                        wrk.setRol(Rol.valueOf(request.getParameter("rol")));
                        wrkmng.saveWorks(wrk);
                    }
                    break;
                case "Update":
                    if (wrk != null) {
                        wrk.setDateStart(new Date(Calendar.getInstance().getTimeInMillis()));
                        wrk.setRol(Rol.valueOf(request.getParameter("rol")));
                        wrkmng.updateWorks(wrk);
                    }
                default:
                    break;
            }
        } catch (Exception e) {
            String error = "[";
            Enumeration<String> names = request.getParameterNames();
            while (names.hasMoreElements()) {
                final String paramName = names.nextElement();
                final String paramValue = request.getParameter(paramName);
                error = error.concat(paramName + ":" + paramValue + "|");
            }
            error = error.concat("]");
            LOG.error("Error while executing action: " + request.getParameter("action")
                    + " with params: " + error + "\n"
                    , e);
        }

        usrmng.close();
        wrkmng.close();
        prjmng.close();

        request.setAttribute("usrid", request.getParameter("user"));

        doGet(request, response);
    }
}
